﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SharePoint.Administration;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.Utilities;
using System.Data;


namespace iwss.Document
{
    public static class Utilitys
    {
        public enum ImageSize
        {
            Thumbnail,
            Large,
            Full
        }
        /// <summary>
        /// 账号
        /// </summary>
        /// <param name="accountName"></param>
        /// <returns></returns>
        public static string GetAccountName(string accountName)
        {
            string result = accountName;
            string charsToReplace = @"\/:*?""<>|#";
            Array.ForEach(charsToReplace.ToCharArray(), charToReplace => result = result.Replace(charToReplace, '_'));
            return result;
        }

        public static DataTable TableFilter(string key, DataTable TableData)
        {
            return TableFilter(key, null, TableData);
        }
        public static DataTable TableFilter(string key, List<string> fields, DataTable TableData)
        {
            DataTable newFilterTable = TableData.Clone();

            int rowCount = TableData.Rows.Count;
            int columnCount = TableData.Columns.Count;
            string CurrentField = string.Empty;

            for (int i = 0; i < rowCount; i++)
            {
                DataRow dr = TableData.Rows[i];
                for (int a = 0; a < columnCount; a++)
                {
                    if (fields != null)
                    {
                        CurrentField = TableData.Columns[a].ColumnName;
                        if (!fields.Contains(CurrentField))
                            continue;
                    }

                    if (dr[a].EToString().IndexOf(key) != -1)
                    {
                        AddNewRow(newFilterTable, dr);
                        break;
                    }
                }
            }

            return newFilterTable;
        }

        private static void AddNewRow(DataTable dt, DataRow dr)
        {
            DataRow newRow = dt.NewRow();
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                newRow[i] = dr[i];
            }
            dt.Rows.Add(newRow);
        }

        public static string GetPictureUrl(SPListItem listItem, ImageSize imageSize)
        {
            StringBuilder url = new StringBuilder();
            // Build the url up until the final portion
            url.Append(SPEncode.UrlEncodeAsUrl(listItem.Web.Url));
            url.Append('/');
            url.Append(SPEncode.UrlEncodeAsUrl(listItem.ParentList.RootFolder.Url));
            url.Append('/');
            // Determine the final portion based on the requested image size
            string filename = listItem.File.Name;
            if (imageSize == ImageSize.Full)
            {
                url.Append(SPEncode.UrlEncodeAsUrl(filename));
            }
            else
            {
                string basefilename = Path.GetFileNameWithoutExtension(filename);
                string extension = Path.GetExtension(filename);
                string dir = (imageSize == ImageSize.Thumbnail) ? "_t/" : "_w/";
                url.Append(dir);
                url.Append(SPEncode.UrlEncodeAsUrl(basefilename));
                url.Append(SPEncode.UrlEncodeAsUrl(extension).Replace('.', '_'));
                url.Append(".jpg");
            }
            return url.ToString();
        }

        public static string GetIcon(string path)
        {
            return "/_Layouts/images/"+SPUtility.MapToIcon(SPContext.Current.Web, path, string.Empty, Microsoft.SharePoint.Utilities.IconSize.Size16);
        }
        /// <summary>
        /// 处理URL为绝对地址
        /// /Lists/Tasks 转换为 http://moss/Lists/Tasks
        /// </summary>
        /// <param name="listUrl">Example: /Lists/Tasks</param>
        /// <returns></returns>
        public static string FixUrl(string listUrl)
        {
            if (!listUrl.StartsWith("/"))
                listUrl = "/" + listUrl;
            return Microsoft.SharePoint.Utilities.SPUtility.GetServerRelativeUrlFromPrefixedUrl("~site" + listUrl);
        }

        public static SPList GetListByAdmin(Guid siteID, Guid webID, Guid ListID)
        {
            SPList list = null;
            RunCodeByAdmin(() =>
            {
                using (SPSite site = new SPSite(siteID))
                {
                    using (SPWeb web = site.AllWebs[webID])
                    {
                        list = web.Lists[ListID];
                    }
                }
            });
            return list;
        }
        public static SPList GetListByAdmin(Guid webID, Guid id)
        {
            return GetListByAdmin(SPContext.Current.Site.ID, webID, id);
        }
        public static SPList GetListByAdmin(Guid id)
        {
            return GetListByAdmin(SPContext.Current.Site.ID, SPContext.Current.Web.ID, id);
        }

        public static SPList GetListByAdmin(Guid siteID, Guid webID, string ListTitle)
        {
            SPList list = null;
            RunCodeByAdmin(() =>
            {
                using (SPSite site = new SPSite(siteID))
                {
                    using (SPWeb web = site.AllWebs[webID])
                    {
                        list = web.Lists.TryGetList(ListTitle);
                    }
                }
            });
            return list;
        }
        public static SPList GetListByAdmin(Guid webID, string ListTitle)
        {
            return GetListByAdmin(SPContext.Current.Site.ID, webID, ListTitle);
        }
        public static SPList GetListByAdmin(string ListTitle)
        {
            return GetListByAdmin(SPContext.Current.Site.ID, SPContext.Current.Web.ID, ListTitle);
        }


        public static void RunCodeByAdmin(SPSecurity.CodeToRunElevated action)
        {
            SPSecurity.RunWithElevatedPrivileges(action);
        }

        public static string GetCreateTime(SPListItem p, string fieldName)
        {
            if (p[fieldName] == null) return DateTime.Now.ToString();
            DateTime time = (DateTime)p[fieldName];
            return string.Format("{0}/{1}", time.Month, time.Day);
        }

        public static string GetUserName(object obj)
        {
            string str = string.Empty;

            if (obj is SPUser)
                str = ((SPUser)obj).Name;

            str = GetAccountName(obj.EToString());

            if (str.IndexOf('_') != -1)
            {
                return str.Split('_').Last();
            }

            return obj.EToString();
        }

        public static string ConvertTimeToCmal(DateTime time)
        {
            //string temp = string.Format("{0}-{1}-{2} {3}:{4}:{5}", time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second);
            return SPUtility.CreateISO8601DateTimeFromSystemDateTime(time);
        }

        public static string GetFirstDayOfMonth(bool convertToCaml)
        {
            return ConvertTimeToCmal(GetFirstDayOfMonth());
        }

        public static string GetLastDayOfMonth(bool convertToCaml)
        {
            return ConvertTimeToCmal(GetLastDayOfMonth());
        }

        public static DateTime GetFirstDayOfMonth()
        {
            DateTime firstDay = DateTime.Now.AddDays(-DateTime.Now.Day);
            if (firstDay.DayOfWeek != DayOfWeek.Sunday)
            {
                int intday = Convert.ToInt32(firstDay.DayOfWeek) + 1;
                return firstDay.AddDays(-intday);
            }
            return firstDay;
        }

        public static DateTime GetLastDayOfMonth()
        {
            DateTime lastDay = GetFirstDayOfMonth().AddMonths(1).AddDays(-1); ;
            if (lastDay.DayOfWeek != DayOfWeek.Saturday)
            {
                int intday = Convert.ToInt32(lastDay.DayOfWeek) + 1;
                return lastDay.AddDays(intday);
            }
            return lastDay;
        }

        /// <summary>
        /// 根据目录新建文件夹，路径中每一个文件夹都会查检和创建 
        /// </summary>
        /// <param name="FolderUrl">如：DocLib/XXXXX/DDDD/333</param>
        public static void RecursionCreateFolder(string FolderUrl, string netPath)
        {
            FolderUrl = FolderUrl.Replace('/', '\\').Replace("\\\\", "\\");
            //TraceProvider.LogInfo("检查路径是否存在：" + FolderUrl);
            try
            {
                string[] UrlSpell = FolderUrl.Split(new string[1] { "\\" }, StringSplitOptions.RemoveEmptyEntries);

                if (!netPath.IsNullOrEmpty() && !netPath.EndsWith("\\"))
                    netPath += "\\";

                string tempUrl = string.Empty;
                for (int i = 0; i < UrlSpell.Length; i++)
                {
                    string cfolder = string.Format("{0}\\{1}", tempUrl, UrlSpell[i]);

                    if (!Directory.Exists(netPath + cfolder))
                    {
                        CreateFolder(netPath + cfolder);
                    }

                    tempUrl = cfolder;
                }
            }
            catch (Exception ex)
            {
                TraceProvider.LogError(ex);
            }
        }
        /// <summary>
        /// 反序列化
        /// </summary> 
        public static object Reserialize(string fileUrl)
        {
            if (!File.Exists(fileUrl)) return null;
            using (FileStream fs = new FileStream(fileUrl, FileMode.Open))
            {
                BinaryFormatter bf = new BinaryFormatter();
                if (fs.Length <= 0)
                {
                    return null;
                }
                return bf.Deserialize(fs);
            }
        }

        /// <summary>
        /// 序列化
        /// </summary>
        public static void Serialize(string fileUrl, object listPers)
        {
            using (FileStream fs = new FileStream(fileUrl, FileMode.Create))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, listPers);
            }
        }


        /// <summary>
        /// 获取内容
        /// </summary>
        /// <returns></returns>
        public static List<string> GetImageUrls(string str)
        {
            Regex reg = new Regex(@"src\=.+?\.(jpg|gif|png|bmp|jpeg)");
            MatchCollection mc = reg.Matches(str);
            List<string> urls = new List<string>();
            foreach (Match m in mc)
            {
                urls.Add(m.Value.Replace("src=\"", ""));
            }
            return urls;
        }

        /// <summary>
        /// 获取内容
        /// </summary>
        /// <returns></returns>
        public static string GetImageUrl(string str)
        {
            List<string> urls = GetImageUrls(str);
            if (urls.Count > 0)
                return urls[0];

            return string.Empty;
        }

        public static string GetItemUrl(SPListItem item)
        {

            // http://cnuportal/_layouts/listform.aspx?PageType=4&ListId={A12F1F3F-C591-48CF-A909-B893CEA7A764}&ID=1
            //return string.Format("{0}?PageType=4&ListId={1}&ID={2}", SPUtility.ConcatUrls(item.ParentList.ParentWeb.Url, 
            //    item.ParentList.DefaultDisplayFormUrl)
            //    , item.ParentList.ID, item.ID);
            return string.Format("{0}?PageType=4&ListId={1}&ID={2}", item.ParentList.DefaultDisplayFormUrl
                , item.ParentList.ID, item.ID);
        }

        public static string GetFormatDateString(object obj)
        {
            DateTime dtstr = DateTime.Now;

            if (DateTime.TryParse(obj.EToString(), out dtstr))
            {
                return string.Format("{0}:{1}", dtstr.Hour, Utilitys.CreateProfix(dtstr.Minute, 1, true));
            }
            return dtstr.ToShortTimeString();
        }


        public static object CreateProfix(object obj, int num, bool left)
        {
            if (obj.EToString().Length == num)
            {
                if (left)
                    return "0" + obj;
                else
                    return obj + "0";
            }
            else
                return obj;
        }

        public static void CreateFolder(string tempUrl)
        {
            tempUrl = "\\" + tempUrl.Replace("\\\\", "\\");
            //TraceProvider.LogInfo("正在创建：" + tempUrl);
            Directory.CreateDirectory(tempUrl);
        }

        public static string TranslateDocUrl(SPFolder folder)
        {
            string RootFolderName = folder.DocumentLibrary.RootFolder.Name;
            string folderUrl = folder.Url;
            if (folderUrl.StartsWith("/"))
                folderUrl = folderUrl.Substring(1);
            if (!folderUrl.StartsWith(RootFolderName))
                return folderUrl;
            folderUrl = folderUrl.Replace('/', '\\');

            //var cnUrl = string.Format(@"\{0}\{1}\{2}", folder.ParentWeb.Title, folder.DocumentLibrary.Title, folderUrl.Substring(RootFolderName.Length));
            return folderUrl.Substring(RootFolderName.Length);
        }

        public static string TranslateDocUrl(SPFile spFile)
        {
            //邮件2012/12/18 (周二) 15:14  客户提出 取消显示 站点名字+文档库名字
            //string translatedFolderUrl = TranslateDocUrl(spFile.ParentFolder);

            string RootFolderName = spFile.DocumentLibrary.RootFolder.Name;
            string folderUrl = spFile.Url;
            if (folderUrl.StartsWith("/"))
                folderUrl = folderUrl.Substring(1);
            if (!folderUrl.StartsWith(RootFolderName))
                return folderUrl;
            folderUrl = folderUrl.Replace('/', '\\').Substring(RootFolderName.Length);

            return folderUrl;// string.Format(@"{0}\{1}", translatedFolderUrl, spFile.Name);
        }


        public static void SendEmail(Guid siteID, string pSubject, string pFrom, string pTo, string pBody)
        {

            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

            message.IsBodyHtml = true;
            message.Body = pBody;
            message.From = new System.Net.Mail.MailAddress(pFrom);
            message.To.Add(pTo);
            message.Subject = pSubject;

            using (SPSite site = new SPSite(siteID))
            {
                SPOutboundMailServiceInstance smtpServer = site.WebApplication.OutboundMailServiceInstance;
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpServer.Server.Address);
                smtp.Send(message);
            }
        }

        /// <summary>
        /// 根据目录新建文件夹，路径中每一个文件夹都会查检和创建
        /// </summary>
        /// <param name="FolderUrl">  /DocLib/XXXXX/DDDD/333</param>
        public static SPFolder CreateSPFolder(string FolderUrl)
        {
            string[] UrlSpell = FolderUrl.Split(new string[1] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            SPFolder folder = null;
            string tempUrl = SPContext.Current.Web.Url;

            for (int i = 0; i < UrlSpell.Length; i++)
            {
                string turlpar =  UrlSpell[i];
                SPFolder cfolder = SPContext.Current.Web.GetFolder(String.Format("{0}/{1}", tempUrl, turlpar));
                if (!cfolder.Exists)
                {
                    folder = CreateSPFolder(cfolder.ParentFolder, turlpar);
                }

                tempUrl = String.Format("{0}/{1}", tempUrl, turlpar);
            }

            return folder;
        }

        private static SPFolder CreateSPFolder(SPFolder cfolder, string p)
        {
            cfolder.ParentWeb.AllowUnsafeUpdates = true;
            SPFolder f = cfolder.SubFolders.Add(p);
            cfolder.ParentWeb.AllowUnsafeUpdates = false;
            return f;
        }

        private static SPFolder CreateSPFolder(string parentUrl, string fname)
        {
            return CreateSPFolder(SPContext.Current.Web.GetFolder(parentUrl), fname);
        }
    }
}
